package com.aaa.controller;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.entity.Result;
import com.aaa.service.RoleService;
import com.aaa.service.impl.RoleServiceImpl;
import com.aaa.util.MyTool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈
 * @date ：Created in 2020/9/24 9:01
 * @description：角色servlet
 * @modified By：
 * @version: 1.0
 */
@WebServlet(name = "RoleServlet",urlPatterns = "/role")
public class RoleServlet extends HttpServlet {
    RoleService roleService= new RoleServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        //获取所有的参数，保存到map<String,String>
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            //如果当前key对象的value不为空，将key和value存入新的map<String，String>
            if (!ObjectUtil.isEmpty(entry.getValue()) && entry.getValue()[0].length() > 0) {
                map.put(entry.getKey(), entry.getValue()[0]);
            }
        }
        //获取参数
        String method = req.getParameter("method");
        String jsonString = "";
        Result result = new Result();
        switch (method) {
            //查询所有的角色
            case "findAllRole":
                List<Map<String, Object>> allRole = roleService.findAllRole();
                result = MyTool.getSuccessReturn(result);
                result.setData(allRole);
                //在转换json字符串的时候，格式化日期
                 jsonString = JSON.toJSONString(result, SerializerFeature.UseISO8601DateFormat);
                break;
                //添加角色
            case "saveRole":
                boolean saveRole = roleService.saveRole(map);
                if(saveRole){
                    result = MyTool.getSuccessReturn(result);
                }else
                {
                    result = MyTool.getFailedReturn(result);
                }
                jsonString = JSON.toJSONString(result);
                break;
        }
        resp.getWriter().print(jsonString);
    }
}
